from django import template
register = template.Library()
from sorl.thumbnail.main import DjangoThumbnail
from django.utils.safestring import mark_safe
from utils import common_query

def thumbnail(value):
    '''
    Filter to generate thumbnail of image
    By default size (200, 200)
    '''
    try:
        t = DjangoThumbnail(relative_source=value, requested_size=(130,130))
        img_url = t.absolute_url
        img_url = img_url.split('/media/')[1]
        output = []
        output.append((u'''<img class="profilImgSize" src="http://127.0.0.1:8000/static_media/%s" />''' % (img_url)))
        return mark_safe(u''.join(output))
    
    except:
        output = []
        output.append(u'''<img class="profilImgSize" src="http://127.0.0.1:8000/static_media/photo/NoImage_jpg_200x200_q85.jpg" />''')
        return mark_safe(u''.join(output))
        
register.filter('thumbnail', thumbnail)

# Group Portrait
def portrait_img(value):
    '''
    Filter to generate thumbnail of image
    By default size (130, 130)
    '''
    try:
        img_url = value.split('site_media/')[1]
        output = []
        output.append((u'''<img class="profilImgSize" src="http://127.0.0.1:8000/static_media/%s" />''' % (img_url)))
        return mark_safe(u''.join(output))
        
    except:
        output = []
        output.append(u'''<img class="profilImgSize" src="http://127.0.0.1:8000/static_media/photo/NoImage_jpg_200x200_q85.jpg" />''')
        return mark_safe(u''.join(output))
        
register.filter('portrait_img', portrait_img)

def user_profile(value):
    # Filter to generate link to user profile

    # Get User row fram cache
    # value is userid
    member_data = common_query.get_group_member(value, False)
    try:
        output = []
        output.append((u'''<a class="" href="http://127.0.0.1:8000/connectpeople/profile/%s" >''' % (value) + member_data[0].first_name + ' ' + member_data[0].last_name +'''</a>'''))
        return mark_safe(u''.join(output))
    
    except:
        output = []
        output.append(u'''<img class="" href="http://127.0.0.1:8000/connectpeople/home/" >''' + member_data[0].first_name + ' ' + member_data[0].last_name +'''</a>''')
        return mark_safe(u''.join(output))
        
register.filter('user_profile', user_profile)
